<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <ringochan@jxlnxx.com> <http://www.jxlnxx.com/>
// +----------------------------------------------------------------------

namespace Api\Controller;

/**
 * API鉴真宝控制器
 * 主要获取鉴定商品数据
 *
 * @author Ringo Chan <ringochan@jxlnxx.com>
 */
class CheckupController extends ApiController{
    /*
     * 生成订单号
     *
     */
    function build_checkup_no()
    {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
         
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }
    
    /**
     * 发布鉴定
     * 
     * @author Ringo Chan <ringochan@jxlnxx.com>
     */
    public function add(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        params_exist(array('title','category_id', 'quantity', 'description', 'province_id', 
            'city_id', 'area_id', 
            'address', 'mobile', 'realname','pic'));
        $data = params_post(array('title','category_id', 'quantity', 'description',
            'province_id',
            'city_id', 'area_id', 'address', 'mobile',
            'realname',
            'pic'));
     
        !(preg_match('/.{4,60}$/', $data['title'])) && response(-1, '', '标题2-50字这间');
        !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
        !(preg_match('/[\d]+$/', $data['quantity']) && intval($data['quantity']) >= 0) && response(-1, '', '请输入商品库存，不能小于0');
        !get_table_field($data['province_id'], 'province_id', 'province_id', 'hat_province') && response(-2, '', '请选择发货地的省份');
        !get_table_field($data['city_id'], 'city_id', 'city_id', 'hat_city') && response(-2, '', '请选择发货地的城市');
        !get_table_field($data['area_id'], 'area_id', 'area_id', 'hat_area') && response(-2, '', '请选择发货地的区县');
        !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $data['address']) && response(-1, '', '详细地址长度必须在2~50个字符');
        !preg_match('/1[34578]{1}\d{9}$/', $data['mobile']) && response(-1, '', '联系电话为手机号码，请您正确填写');
        !preg_match('/^[\x{4e00}-\x{9fa5}]{1,4}+$/u', $data['realname']) && response(-1, '', '请正确填写您的姓名');
        
        $data['uid']=API_UID;
        $data['create_time']=NOW_TIME;
        $data['status']=0;
        $data['identify_price'] = get_table_field($data['category_id'],'product_category_id','price','identify') | 0;
        
        $data['shipping_price']=get_table_field($data['province_id'],'province_id','price',
            'shipping_price')|0;
        $data['checkup_no']=$this->build_checkup_no();
        $data['total']=(double)$data['identify_price'] * (int)$data['quantity'] + (double)$data['shipping_price'];
        $M_checkup = M('checkup');
        $M_checkup_image = M('checkup_image');
        $M_checkup_movie = M('checkup_movie');
        
        $id = $M_checkup->add($data);
        
        $id <= 0 && response(-9);
        
        $pics = $data['pic'];
        !is_array($pics) && $pics = array($pics);
        foreach ($pics as $pic) {
            $M_checkup_image->add(array('checkup_id'=>$id, 'cover_id'=>$pic));
        }
        
        $movies = I('post.movie');
        !is_array($movies) && $movies = array($movies);
        foreach ($movies as $movie) {
            $M_checkup_movie->add(array('checkup_id'=>$id, 'cover_id'=>$movie));
        }
        

        response(1,$id);
    }
    
    /**
     * 鉴定列表
     * @param string token
     * @param int category_id 商品类型id
     * @param int status
     * @param int page=1
     * @param int pagesize=10
     */
    public function MyCheckupList(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
     
        $page = I('post.page', 1); // 页码
        (int)$page <=0 && $page=1;        
        $pagesize = I('post.pagesize', 10); // 分页显示条数
        (int)$pagesize <=0 && $pagesize=10;        
        $offset=($page-1)*$pagesize;
        
       
        $category_id=I('post.category_id');
        
        $M_checkup = M('checkup');
        $M_checkup_image = M('checkup_image');
        $M_checkup_movie = M('checkup_movie');
        $M_identify = M('identify');
       
        $status=I('post.status');
    
        $map=array();
        $map['uid']=API_UID;
        $map['is_show']=1;
        if($status !==''){
            $map['status']=$status;
        }
       
        $total=$M_checkup->where($map)->count();
      
        if($category_id){
            !empty(get_table_field($category_id, 'id', 'id', 'product_type')) && response(-2, '', '无效商品类型');
            $map['category_id']=$category_id;
        }
       
        $list=$M_checkup->limit($offset,$pagesize)->where($map)->select();
      
        foreach($list as &$item){
            $tem_cover_id=$M_checkup_image
            ->where(array('checkup_id'=>$item['id']))->getfield('cover_id');
            $item['image'][]=get_url($tem_cover_id);     
            
            $tem_mov_id=$M_checkup_movie
            ->where(array('checkup_id'=>$item['id']))->getfield('cover_id');
            if($tem_mov_id){
                $item['movie'][] = array(
                    'id' => $tem_mov_id,
                    'path' =>  get_movie($tem_mov_id, 'savepath') ? mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")) . '/Upload/Movie/' . get_movie($tem_mov_id, 'savepath') . get_movie($tem_mov_id, 'savename') : '',
                    'mime' => get_movie($tem_mov_id, 'mime')
                );
            }else{
                $item['movie']=null;
            }
            
            
        }
        
        $result=array();
        $result['total']=$total;
        $list=int_to_string($list,array('status'=>getStatus('checkup_status')));
        $result['result']=$list;
        $list ? response(1,$result) : response(-2);
    }
    /*
     * 获取鉴定详情
     * @param int checkup_id 鉴定id
     */
    public function CheckupDetail(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array('checkup_id'));        
        $id = I('post.checkup_id', 0);        
        
        $M_checkup=M('checkup');
        $M_checkup_image=M('checkup_image');
        $M_check_movies=M('checkup_movie');
        
        $map=array();
        $map['uid']=API_UID;
        $map['id']=$id;
        $map['is_show']=1;
        
        $info=$M_checkup->where($map)->find();
        
        empty($info) && response(-2,'鉴定的商品不存在');
        
      
        $info['category']=get_table_field($info['category_id'],'id','title','product_category');
        $info['address_full']=
        get_table_field($info['province_id'],'province_id','province','hat_province')
        .get_table_field($info['city_id'],'city_id','city','hat_city')
        .get_table_field($info['area_id'],'area_id','area','hat_area')
        .$info['address'] ;
        $info['format_time']=time_format($info['create_time'],'Y-m-d H:m:s');
        $images = $M_checkup_image->where(array('checkup_id'=>$id))->select();
        foreach ($images as $image) {
            $info['images'][] = array(
                'path' => get_url($image['cover_id'])
            );
        }
        $movies = $M_check_movies->where(array('checkup_id'=>$id))->select();
        foreach ($movies as $movie) {
             $info['movie'][] = array(
            'id' => $movie['id'],
            'path' => mb_substr($_SERVER["HTTP_REFERER"], 0, 
                strrpos($_SERVER["HTTP_REFERER"], "/")) . '/Upload/Movie/' 
                 . get_movie($movie['cover_id'], 'savepath') 
                 . get_movie($movie['cover_id'], 'savename'),
            'mime' => get_movie($movie['cover_id'], 'mime')
        );
        }
        
        $status=getStatus('checkup_status');
        $info['status_text']=$status[$info['status']];
             
        response(1, $info);
    }
    
    /**
     * 鉴定发货
     * @param int checkup_id
     * @param int shipping_code
     * @param string code
     * @param int cover_id[]
     */
    public function Shipments(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array('checkup_id','shipping_code','code'));
        $cover_id=I('post.cover_id');
        is_array($cover_id)  && $cover_id =implode(',',$cover_id);
    
        $data = params_post(array('checkup_id', 'shipping_code','code'));
        !get_table_field($data['checkup_id'],'id','id','checkup') && response(-2,'','鉴定单不存在');
    
        $data['type']='seller';
        $data['create_time']=NOW_TIME;
        $data['cover_ids']=$cover_id;  
         
        $M_checkup=M('checkup');
        $M_checkup_shipping=M('checkup_shipping');
         
        $M_checkup->where(array('id'=>$data['checkup_id']))->setField('status',2);
         
        if($M_checkup_shipping->where(array('checkup_id'=>$data['checkup_id']))->find()){    
            $result=$M_checkup_shipping->where(array('checkup_id'=>$data['checkup_id']))->save($data);
            empty($result) && response(-9);
        }else{
            $data['checkup_id']=$data['checkup_id'];
            $result= $M_checkup_shipping->add($data);
            empty($result) && response(-9);
        }
        response(1);
    }
    
    /**
     * 删除鉴定
     * @param int checkup_id
     */
    public  function delCheckup(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array('checkup_id'));
        
        $check_id=I('post.checkup_id');        
        $M_checkup=M('checkup');
        
        $map=array('uid'=>API_UID,'id'=>$check_id);
        $info=$M_checkup->where($map)->find();
        empty($info) && response(-2,'','鉴定不存在');
        
        $result=$M_checkup->where($map)->save(array('is_show'=>0));
        $result !==false  && response(1);
        response(-9);
    }
    
}
?>